import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card} from 'antd';
import {FORM_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {saleOrderForecastSummaryWay} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import ProductCategorySelectPanel from './ProductCategorySelectPanel';
import MarketDepartmentSelectPanel from './MarketDepartmentSelectPanel';
import ProductSelectPanel from './ProductSelectPanel';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import WrappedInputNumber from '../common/WrappedInputNumber';
import Export from '../common/Export';
import {injectIntl, language} from './intl';
const FormItem = Form.Item;

class QueryPanel extends React.PureComponent {
    state = {
        data: {
            materialGroupCode: '',
            marketDepartmentName: '',
            modelName: '',
        },
        showProductCategorySelectPanel: false,
        showMarketDepartmentSelectPanel: false,
        showProductSelectPanel: false,
        
    }
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterChanges = (value, name) => {
        if(this.props.conditions.saleOrderForecastSummaryWay !== value)
            this.props.onConditionsChanges(name, value);
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    reset = () => {
        this.setState({
            data: {
                materialGroupCode: '',
                marketDepartmentName: '',
                modelName: '',
            },
        });
        this.props.onResetClick();
    }
    onSelectDealer = data => {
        this.handleFilterChange(data.id, 'dealerId');
        this.props.onSelect({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    onClickSearchProductCategoryBtn = () => {
        this.setState({
            showProductCategorySelectPanel: true
        });
    }
    onClickSearchMarketDepartmentBtn = () => {
        this.setState({
            showMarketDepartmentSelectPanel: true
        });
    }
    onClickSearchProductBtn = () => {
        this.setState({
            showProductSelectPanel: true
        });
    }
    onCloseProductCategorySelectPanel = () => {
        this.setState({showProductCategorySelectPanel: false});
    }
    onCloseMarketDepartmentSelectPanel = () => {
        this.setState({showMarketDepartmentSelectPanel: false});
    }
    onCloseProductSelectPanel = () => {
        this.setState({showProductSelectPanel: false});
    }
    onSelectProductCategory = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                materialGroupId: records.id,
                materialGroupCode: records.materialGroupCode,
            }),
            hasOperat: true,
            showProductCategorySelectPanel: false
        });
        this.props.onConditionsChange('materialGroupId', records.id);
    }
    onSelectMarketDepartment = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                marketDepartmentId: records.id,
                marketDepartmentName: records.name,
            }),
            hasOperat: true,
            showMarketDepartmentSelectPanel: false
        });
        this.props.onConditionsChange('marketDepartmentId', records.id);
    }
    onSelectProduct = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                modelId: records.id,
                modelName: records.name,
            }),
            hasOperat: true,
            showProductSelectPanel: false
        });
        this.props.onConditionsChange('modelId', records.id);
    }
    render() {
        const {data} = this.state;
        const {formatMessage} = this.props.intl;
        const {brands} = this.props.initEnumData;
        const condition = this.props.conditions || {};
        const dealerInfo = condition.dealerId ? {
            id: this.props.queryDealer.id,
            code: this.props.queryDealer.code,
            name: this.props.queryDealer.name
        } : null;
        return (
            <div>
                <Form className="form-standard">
                    <Card>
                        <Row>
                            {brands.length !== 1 && <Col {...FORM_OPTIONS.col}><FormItem label={formatMessage({
                                id: 'queryPanel.form.brandId',
                                defaultMessage: '品牌'
                            })}{...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.conditions.brandId}
                                    options={brands}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                            </Col>}
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.marketDepartmentId',
                                        defaultMessage: '大区'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <SearchInput
                                        disabled={true}
                                        id={data.id}
                                        value={data.marketDepartmentName}
                                        onClickSearchBtn={this.onClickSearchMarketDepartmentBtn}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DealerSelectPanel
                                        value={dealerInfo}
                                        onSelect={this.onSelectDealer} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.forecastYear',
                                        defaultMessage: '预测年份'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedInputNumber
                                        min={0}
                                        precision={0}
                                        name="forecastYear"
                                        value={this.props.conditions.forecastYear}
                                        onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.forecastMonth',
                                        defaultMessage: '预测月份'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedInputNumber
                                        name="forecastMonth"
                                        value={this.props.conditions.forecastMonth}
                                        onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.materialGroupId',
                                        defaultMessage: '物料组号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <SearchInput
                                        disabled={true}
                                        id={data.id}
                                        value={data.materialGroupCode}
                                        onClickSearchBtn={this.onClickSearchProductCategoryBtn}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.kDBOMCode',
                                        defaultMessage: 'KDBOM编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="kDBOMCode"
                                        value={this.props.conditions.kDBOMCode}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.handleFilterChange}/>
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.modelId',
                                        defaultMessage: '车型'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <SearchInput
                                        disabled={true}
                                        id={data.id}
                                        value={data.modelName}
                                        onClickSearchBtn={this.onClickSearchProductBtn}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.saleOrderForecastSummaryWay',
                                        defaultMessage: '汇总方式'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedSelect
                                        allowClear
                                        name="saleOrderForecastSummaryWay"
                                        value={this.props.conditions.saleOrderForecastSummaryWay}
                                        options={saleOrderForecastSummaryWay.toList(language)}
                                        onChange={this.handleFilterChanges} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6}>
                                <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>{formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}</Button>
                                <Button key="clear" onClick={this.reset}>{formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}</Button>
                            </Col>
                            <Col span={18} className="col-align-right">
                                {this.props.exportable && <Export key={PERMISSION.export} exportRequest={this.props.onClickExport} />}
                            </Col>
                        </Row>
                        {
                            this.state.showMarketDepartmentSelectPanel &&
                    <MarketDepartmentSelectPanel
                        onCancel={this.onCloseMarketDepartmentSelectPanel}
                        onSelect={this.onSelectMarketDepartment} />
                        }
                        {
                            this.state.showProductCategorySelectPanel &&
                    <ProductCategorySelectPanel
                        onCancel={this.onCloseProductCategorySelectPanel}
                        onSelect={this.onSelectProductCategory} />
                        }
                        {
                            this.state.showProductSelectPanel &&
                    <ProductSelectPanel
                        onCancel={this.onCloseProductSelectPanel}
                        onSelect={this.onSelectProduct} />
                        }
                    </Card>
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    querySearch: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onConditionsChanges: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {saveQueryCondition, saveQueryConditions, querySearch, resetQueryPanel, saveQueryDealer, exportData} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: item.name,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    initEnumData: getinitEnumData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    exportable: state.getIn(['page', 'domainData', 'permission', 'data']).includes(PERMISSION.export),
    queryDealer: getQueryDealer(state),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onConditionsChanges: (name, value) => dispatch(saveQueryConditions(name, value)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
    onSelect: data => dispatch(saveQueryDealer(data)),
    onClickExport: () => dispatch(exportData())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
